'use strict';
exports.main = async (event, context) => {
  const db = uniCloud.database()
  const {
    keyword = '',
    status,
    date,
    page = 1,
    pageSize = 10
  } = event

  let where = {}

  try {
    // 修复关键词搜索
    if (keyword) {
      where.$or = [
        { username: { $regex: keyword, $options: 'i' } }, // 直接使用字符串
        { mobile: { $regex: keyword, $options: 'i' } }
      ]
    }

    // 状态过滤保持不变
    if (status && status !== '') {
      where.status = status === 'normal' ? 1 : 0
    }

    // 修复时间筛选
    if (date) {
      const targetDate = new Date(date)
      if (!isNaN(targetDate)) {
        const start = new Date(targetDate.setHours(0, 0, 0, 0)).getTime()
        const end = new Date(targetDate.setHours(23, 59, 59, 999)).getTime()
        where.createTime = { $gte: start, $lte: end }
      }
    }

    // 查询配置保持不变
    const collection = db.collection('user')
      .where(where)
      .orderBy('createTime', 'desc')
      .field({
        _id: true,
        username: true,
        mobile: true,
        avatar: true,
        status: true,
        createTime: true,
        role: true
      })

    // 并行查询
    const [dataRes, countRes] = await Promise.all([
      collection.skip((page - 1) * pageSize).limit(pageSize).get(),
      collection.count()
    ])

    return {
      code: 0,
      data: {
        list: dataRes.data,
        total: countRes.total
      }
    }

  } catch (error) {
    console.error('云函数错误:', error)
    return {
      code: 500,
      message: '服务器内部错误',
      error: error.message
    }
  }
}